<?php


namespace app\common\model;


use think\Model;
use traits\model\SoftDelete;
use think\Db;

class UserLuckdrawLog extends Model
{

    // 表名
    protected $name = 'user_luckdraw_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    protected $dateFormat = 'Y-m-d H:i:s';

    // 定义时间戳字段名
    protected $createTime = 'create_dt';
    protected $updateTime = 'update_dt';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
    ];
    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getTypeList()
    {
        return ['1' => '获得抽奖次数', '2' => '使用抽奖次数'];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getList($userId, $page = 1, $extend = [], $pageSize = 20)
    {
        $start = ($page - 1) * $pageSize;
        $where = ['user_id' => $userId];
        $where = array_merge($where, $extend);
        $list = $this->where($where)->page($page, $pageSize)->order("id", "desc")->select();
        return $list ?? [];
    }

    /**
     * 添加抽奖次数变动记录
     * @param $userId int 商家ID
     * @param $type int 变动类型:1-获取抽奖次数2-使用抽奖次数
     * @param $trans_no     关联的编号（如订单号，卡券id)
     * @param $memo   string 变动说明
     * @param $num     array 获得的可消耗的次数或获得的吃豆或优惠券数量
     * @return UserLuckdrawLog
     */
    public static function addLog($userId, $type, $trans_no, $memo, $num = 1)
    {
        $user = User::get($userId);
        // 判断有没有达到当日抽奖次数限制
        $luckdraw_chance = config('luckdraw_chance');
        if (isset($luckdraw_chance[$memo]['total_times']) && $luckdraw_chance[$memo]['total_times']) {
            if (self::where(['user_id'=>$userId,'memo'=>$memo,'type'=>1])->count()>=$luckdraw_chance[$memo]['total_times']) {
                return false;
            }
        } elseif (isset($luckdraw_chance[$memo]['daily_times']) && $luckdraw_chance[$memo]['daily_times']) {
            if (self::where(['user_id'=>$userId,'memo'=>$memo,'date'=>date('Ymd'),'type'=>1])->count()>=$luckdraw_chance[$memo]['daily_times']) {
                return false;
            }
        }
        Db::startTrans();
        try {
            if ($type==1) {
                $user->luckdraw_num +=$num;
            } else {
                if ($user->luckdraw_num<1) return false;
                $user->luckdraw_num -=1;
            }
            $user->save();
            $data = [
                'user_id' => $userId,
                'type' => $type,
                'trans_no' => $trans_no,
                'memo' => $memo,
                'num' => $num,
                'date' => date('Ymd'),
            ];
            $return = self::create($data);
            Db::commit();
            return $return;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
            
        }
    }


}